package thread.pool.core.biz;

import thread.pool.core.executor.EmbedServerHolder;
import thread.pool.core.executor.DynamicThreadPoolExecutor;
import thread.pool.core.util.HttpResult;
import thread.pool.core.vo.PoolStatusVo;
import thread.pool.core.vo.UpdateVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

public class ExecutorBizImpl implements ExecutorBiz {
    public ExecutorBizImpl() {
    }

    public HttpResult update(UpdateVo vo) {
        String beanName = vo.getBeanName();
        DynamicThreadPoolExecutor bean = EmbedServerHolder.getBean(beanName, DynamicThreadPoolExecutor.class);
        if (vo.getCorePoolSize() != null) {
            bean.setCorePoolSize(vo.getCorePoolSize());
        }

        if (vo.getMaxPoolSize() != null) {
            bean.setMaxPoolSize(vo.getMaxPoolSize());
        }

        if (vo.getDequeSize() != null && vo.getDequeSize() > 0) {
            bean.setDequeSize(vo.getDequeSize());
        }

        bean.refresh();
        return HttpResult.ok();
    }

    public HttpResult check() {
        Map<String, DynamicThreadPoolExecutor> beansOfType = EmbedServerHolder.getBeansOfType(DynamicThreadPoolExecutor.class);
        List<PoolStatusVo> list = new ArrayList<>();
        beansOfType.forEach((k, v) -> {
            PoolStatusVo poolStatusVo = new PoolStatusVo();
            ThreadPoolExecutor executor = v.getExecutor();
            poolStatusVo.setTaskCount(executor.getQueue().size());
            poolStatusVo.setCorePoolSize(v.getCorePoolSize());
            poolStatusVo.setMaxPoolSize(v.getMaxPoolSize());
            poolStatusVo.setDequeSize(v.getDequeSize());
            poolStatusVo.setPoolName(v.getPoolName());
            poolStatusVo.setBeatTime(v.getBeatTime());
            list.add(poolStatusVo);
        });
        return HttpResult.ok(list);
    }
}
